﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OneBarCode.Utils;
using System.Threading;
using System.IO.Ports;
using System.IO;
using easywork.Utils;
using System.Management;

namespace OneBarCode
{
    public partial class FrmZebra2 : Form
    {
        public FrmZebra2()
        {
            InitializeComponent();
        }
        #region 获取端口名称
        /// <summary>
        /// 枚举win32 api
        /// </summary>
        public enum HardwareEnum
        {
            // 硬件
            Win32_Processor, // CPU 处理器
            Win32_PhysicalMemory, // 物理内存条
            Win32_Keyboard, // 键盘
            Win32_PointingDevice, // 点输入设备，包括鼠标。
            Win32_FloppyDrive, // 软盘驱动器
            Win32_DiskDrive, // 硬盘驱动器
            Win32_CDROMDrive, // 光盘驱动器
            Win32_BaseBoard, // 主板
            Win32_BIOS, // BIOS 芯片
            Win32_ParallelPort, // 并口
            Win32_SerialPort, // 串口
            Win32_SerialPortConfiguration, // 串口配置
            Win32_SoundDevice, // 多媒体设置，一般指声卡。
            Win32_SystemSlot, // 主板插槽 (ISA & PCI & AGP)
            Win32_USBController, // USB 控制器
            Win32_NetworkAdapter, // 网络适配器
            Win32_NetworkAdapterConfiguration, // 网络适配器设置
            Win32_Printer, // 打印机
            Win32_PrinterConfiguration, // 打印机设置
            Win32_PrintJob, // 打印机任务
            Win32_TCPIPPrinterPort, // 打印机端口
            Win32_POTSModem, // MODEM
            Win32_POTSModemToSerialPort, // MODEM 端口
            Win32_DesktopMonitor, // 显示器
            Win32_DisplayConfiguration, // 显卡
            Win32_DisplayControllerConfiguration, // 显卡设置
            Win32_VideoController, // 显卡细节。
            Win32_VideoSettings, // 显卡支持的显示模式。

            // 操作系统
            Win32_TimeZone, // 时区
            Win32_SystemDriver, // 驱动程序
            Win32_DiskPartition, // 磁盘分区
            Win32_LogicalDisk, // 逻辑磁盘
            Win32_LogicalDiskToPartition, // 逻辑磁盘所在分区及始末位置。
            Win32_LogicalMemoryConfiguration, // 逻辑内存配置
            Win32_PageFile, // 系统页文件信息
            Win32_PageFileSetting, // 页文件设置
            Win32_BootConfiguration, // 系统启动配置
            Win32_ComputerSystem, // 计算机信息简要
            Win32_OperatingSystem, // 操作系统信息
            Win32_StartupCommand, // 系统自动启动程序
            Win32_Service, // 系统安装的服务
            Win32_Group, // 系统管理组
            Win32_GroupUser, // 系统组帐号
            Win32_UserAccount, // 用户帐号
            Win32_Process, // 系统进程
            Win32_Thread, // 系统线程
            Win32_Share, // 共享
            Win32_NetworkClient, // 已安装的网络客户端
            Win32_NetworkProtocol, // 已安装的网络协议
            Win32_PnPEntity,//all device
        }
        /// <summary>
        /// WMI取硬件信息
        /// </summary>
        /// <param name="hardType"></param>
        /// <param name="propKey"></param>
        /// <returns></returns>
        public static string[] MulGetHardwareInfo(HardwareEnum hardType, string propKey)
        {

            List<string> strs = new List<string>();
            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + hardType))
                {
                    var hardInfos = searcher.Get();
                    foreach (var hardInfo in hardInfos)
                    {
                        if (hardInfo.Properties[propKey].Value != null) 
                        if (hardInfo.Properties[propKey].Value.ToString().Contains("COM"))
                        {
                            strs.Add(hardInfo.Properties[propKey].Value.ToString());
                        }

                    }
                    searcher.Dispose();
                }
                return strs.ToArray();
            }
            catch
            {
                return null;
            }
            finally
            { strs = null; }
        }
        #endregion
        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                BarcodePrint zb = new BarcodePrint();
                string mycommanglines = System.IO.File.ReadAllText(@"d:\aaa.txt");//print.txt里写了条码机的命令  
                //mycommanglines = "";
                //mycommanglines += "^XA";
                //mycommanglines += "^LH30,30";
                //mycommanglines += "^FO20,10^ADFDZEBRA^FS";
                //mycommanglines += "^FO20,60^B3^FDAAA001^FS";
                //mycommanglines += "^XZ";//^XA^LH30,30^FO20,10^ADFDZEBRA^FS^FO20,60^B3^FDAAA001^FS^XZ
                mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSB^LT0^MNM^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0180\r\n^LS0\r\n^BY2,2,48^FT15,75^B3N,N,,Y,N\r\n^FD" + "LKJIGHABCDEF" + "^FS\r\n^FT30,131^A0N,28,28^FH\\^FDDATE:" + DateTime.Now.ToShortDateString() + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
                zb.Open("COM4:");
                zb.Write(mycommanglines);
                zb.Close(); 
            }
            catch (Exception)
            {
                
                throw;
            }
             
        }



        SerialPort serialPort = null;//当前监听的串口
        int k = 0;//记录当前数据数量
        string currentData = "";//用于存放当前收到的数据
        private void btnReceive_Click(object sender, EventArgs e)
        {
            string comReceiveName = "";
            if (combPortReceive.SelectedIndex>=0)
            {
                comReceiveName = combPortReceive.Text;
            }
            else
            {
                MessageBox.Show("请选择接收数据的端口", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            comReceiveName = comReceiveName.Split('(')[1].Split(')')[0];
            //serialPort = new SerialPort(comReceiveName, 9600, Parity.None, 8, StopBits.One);
            serialPort = new SerialPort(comReceiveName, 115200, Parity.None, 8, StopBits.One);

            //关键 为 serialPort1绑定事件句柄
            serialPort.DataReceived+=new SerialDataReceivedEventHandler(serialPort_DataReceived);
            try
            {
                serialPort.Open();
                lblStatus.Text = "正在监听数据...";
                MessageBox.Show("监听端口成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {

                MessageBox.Show("监听端口失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            
        }

        //数据接收使用的代理
        private delegate void myDelegate(string s);

        //串口数据到达时的事件
        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //关键 代理
            myDelegate md = new myDelegate(SetText);

            try
            {
                if (serialPort.IsOpen == true)
                {
                    byte[] readBuffer = new byte[serialPort.ReadBufferSize];
                    serialPort.Read(readBuffer, 0, readBuffer.Length);
                    string readstr = Encoding.UTF8.GetString(readBuffer);
                    readstr = readstr.Replace("\0", "");
                    currentData += readstr;
                    //return;
                    if (!currentData.StartsWith("0"))//0x
                    {
                        currentData = "";
                    }
                    else
                    {
                        if (currentData.Length>=2&&!currentData.StartsWith("0x"))
                        {
                            currentData = "";
                        }
                    }
                    if (currentData.Length>=33)
                    {
                        if (currentData[30] == 'O')
                        {
                            if (currentData.Length >= 33)
                            {
                                Invoke(md, currentData.Substring(2, 31));
                                currentData = "";
                            }
                        }
                        else if (currentData[30] == 'E')
                        {
                            if (currentData.Length >= 36)
                            {
                                Invoke(md, currentData.Substring(2, 34));
                                currentData = "";
                            }
                        }
                        else
                        {
                            currentData = "";
                        }
                        
                    }
                    //Invoke(md, readstr);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }


        }
        /// <summary>
        /// 向打印机发送打印条码的命令
        /// </summary>
        /// <param name="strMAC"></param>
        private void sendDataToPrinter(string strMAC)
        {
            string strmac = strMAC.Substring(0, 12);
            string comSendName = "";
            if (combPortPrinter.SelectedIndex >= 0)
            {
                comSendName = combPortPrinter.Text;
            }
            BarcodePrint zb = new BarcodePrint();
            string mycommanglines = "";// System.IO.File.ReadAllText(@"d:\aaa.txt");//print.txt里写了条码机的命令  
            mycommanglines = "";
            mycommanglines += "^XA";
            mycommanglines += "^LH30,30";
            mycommanglines += "^FO20,10^ADFDZEBRA^FS";
            mycommanglines += "^FO20,60^B3^FDAAA001^FS";
            mycommanglines += "^XZ";//^XA^LH30,30^FO20,10^ADFDZEBRA^FS^FO20,60^B3^FDAAA001^FS^XZ
            mycommanglines = "I8,A,001\r\n\r\n\r\nQ224,024\r\nq863\r\nrN\r\nS4\r\nD7\r\nZT\r\nJF\r\nO\r\nR279,0\r\nf100\r\nN\r\nB3,29,0,3,2,4,88,B,\"" + strmac + "\"\r\n\r\nP1\r\n";

            mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSB^LT0^MNM^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0180\r\n^LS0\r\n^BY2,2,48^FT15,75^B3N,N,,Y,N\r\n^FD" + strmac + "^FS\r\n^FT30,131^A0N,28,28^FH\\^FDDATE:" + DateTime.Now.ToShortDateString()+"^FS\r\n^PQ1,0,1,Y^XZ\r\n";
            comSendName = comSendName.Split('(')[1].Split(')')[0];
            //zb.Open(comSendName);
            //zb.Write(mycommanglines);
            //zb.Close();
            if (zb.Open(comSendName))
            {
                zb.Write(mycommanglines);
                zb.Close();
            }
            else
            {
                SerialPort serialPortTemp = new SerialPort(comSendName, 9600, Parity.None, 8, StopBits.One);
                //serialPortTemp.Write(mycommanglines);
                serialPortTemp.Open();
                serialPortTemp.WriteLine(mycommanglines);
                serialPortTemp.Close();
            }
        }
        #region MyRegion

        string strSqlTemp = "";
        //分隔字符串并保存在指定目录下
        private void SetText(string str)
        {
            k++;
            if (k==1)
            {
                richTextBox1.AppendText(k + ": " + str+"  "+combStatus.Text); 
            }
            else
            {
                richTextBox1.AppendText("\r\n" + k + ": " + str + "  " + combStatus.Text); 
            }
            richTextBox1.AppendText(" ");
            richTextBox1.ScrollToCaret();
            //将消息存到数据库中
            try
            {
                strSqlTemp = string.Format("insert into HistoryData(Mac,ReceiveTime,Data,Status) values ('{0}','{1}','{2}','{3}')", str.Substring(0, 12), DateTime.Now.ToString(), str,combStatus.Text);
                DataBaseManager.executeNonQuery(strSqlTemp);
            }
            catch (Exception)
            {
                
            }
            if (str[28] == 'O')
            {
                if (combStatus.SelectedIndex==1)
                {
                    sendDataToPrinter(str);
                }
                //sendDataToPrinter(str);
            }
            
        }
        #endregion
        /// <summary>
        /// 停止监听端口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStopReceive_Click(object sender, EventArgs e)
        {
            if (serialPort!=null)
            {
                if(serialPort.IsOpen == true)
                serialPort.Close();
                serialPort.Dispose();
                lblStatus.Text = "已经停止监听端口";
                MessageBox.Show("停止监听端口成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 初始化窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmZebra_Load(object sender, EventArgs e)
        {
            //读取系统的端口初始化端口下拉列表
            //string[] portlist = SerialPort.GetPortNames();
            //portlist=MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name");
            //for (int i = 0; i < portlist.Length; i++)
            //{
            //    this.combPortReceive.Items.Add(portlist[i]);
            //    this.combPortPrinter.Items.Add(portlist[i]);
            //}
            string[] portlistOri = SerialPort.GetPortNames();
            string[] portlist = MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name");
            for (int i = 0; i < portlist.Length; i++)
            {
                for (int k = 0; k < portlistOri.Length; k++)
                {
                    if (portlist[i].Contains(portlistOri[k]))
                    {
                        this.combPortReceive.Items.Add(portlist[i]);
                        this.combPortPrinter.Items.Add(portlist[i]);
                        break;
                    }
                }

                //this.combPortReceive.Items.Add(portlist[i]);
                //this.combPortPrinter.Items.Add(portlist[i]);
            }
            if (combPortReceive.Items.Count>0)
            {
                combPortReceive.SelectedIndex = 0;
            }
            if (combPortPrinter.Items.Count > 0)
            {
                combPortPrinter.SelectedIndex = 0;
            }
            this.combStatus.Items.Add("超声波前");
            this.combStatus.Items.Add("超声波后");
            this.combStatus.SelectedIndex = 0;
        }
        /// <summary>
        /// 清空数据显示区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClear_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            k = 0;
        }
        /// <summary>
        /// 查看历史数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnViewHistory_Click(object sender, EventArgs e)
        {
            FrmHistory frm = new FrmHistory();
            frm.Show();
        }

        private void btnFresh_Click(object sender, EventArgs e)
        {
            this.combPortReceive.Items.Clear();
            this.combPortPrinter.Items.Clear();
            //读取系统的端口初始化端口下拉列表
            string[] portlistOri = SerialPort.GetPortNames();
            string[] portlist = MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name");
            for (int i = 0; i < portlist.Length; i++)
            {
                for (int k = 0; k < portlistOri.Length; k++)
                {
                    if (portlist[i].Contains(portlistOri[k]))
                    {
                        this.combPortReceive.Items.Add(portlist[i]);
                        this.combPortPrinter.Items.Add(portlist[i]);
                        continue;
                    }
                }
                
                //this.combPortReceive.Items.Add(portlist[i]);
                //this.combPortPrinter.Items.Add(portlist[i]);
            }
            if (combPortReceive.Items.Count > 0)
            {
                combPortReceive.SelectedIndex = 0;
            }
            if (combPortPrinter.Items.Count > 0)
            {
                combPortPrinter.SelectedIndex = 0;
            }
        }
    }
}
